<!--
 * @页面名称:个人信息
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="userInfo">
    <el-card style="max-width: 430px; height: 99%">
      <template #header>
        <div class="card-header">
          <h3>账号信息</h3>
        </div>
      </template>
      <div class="userInfo_content">
        <!-- <div class="content_title">账号设置</div> -->
        <img class="content_avatar" :src="avatorUrl" alt="" @click="triggerFileSelect" />
        <div class="content_info">
          <div class="info_item">
            <span class="item_title">用户名：</span>
            <span class="item_content">{{ userInfo.U_Name ? userInfo.U_Name : "--" }}</span>
          </div>
          <div class="info_item">
            <span class="item_title">昵称：</span>
            <span class="item_content">{{ userInfo.U_CName ? userInfo.U_CName : "--" }}</span>
          </div>
          <div class="info_item">
            <span class="item_title">用户邮箱：</span>
            <span class="item_content">{{ userInfo.U_Email ? userInfo.U_Email : "--" }}</span>
          </div>
          <div class="info_item">
            <span class="item_title">手机号：</span>
            <span class="item_content">{{ userInfo.U_Mobile_Num ? userInfo.U_Mobile_Num : "--" }}</span>
          </div>
          <div class="info_item">
            <span class="item_title">绑定IP：</span>
            <span class="item_content">{{ userInfo.U_Binding_IP ? userInfo.U_Binding_IP : "--" }}</span>
          </div>
          <div class="info_item">
            <span class="item_title">角色：</span>
            <!-- <span class="item_content"></span> -->
            <div class="chara">
              <el-tag type="success" v-for="(item, index) in roleData" :key="index" style="margin-right: 8px">{{ item }}</el-tag>
            </div>
          </div>
          <div class="info_item">
            <span class="item_title">登录密码：</span>
            <el-input style="flex: 1" class="item_content" type="password" disabled v-model="userInfo.U_CName"></el-input>
            <span style="width: 90px; color: #409eff; text-align: right; cursor: pointer" @click="resetPassword">修改</span>
          </div>
        </div>
      </div>
    </el-card>
    <el-tabs class="log-card" type="border-card">
      <el-tab-pane label="操作日志">
        <el-table :data="tableData" style="width: 100%" height="100%" :row-class-name="tableRowClassName">
          <el-table-column prop="Log_Time" width="200" label="登录时间" />
          <el-table-column prop="Log_IP" width="120" label="登录IP" />
          <el-table-column prop="Log_Content" label="详细信息">
            <template #default="scope">
              <el-tooltip popper-class="tooltip-pop" effect="dark" :content="scope.row.Log_Content" placement="top">
                <div class="log-content">{{ scope.row.Log_Content }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="Log_Type" label="登录类型" />
          <el-table-column prop="Log_ChangMark" label="登录标记" />
          <!-- <el-table-column prop="Log_Content" label="登录内容" /> -->
        </el-table>
      </el-tab-pane>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-tabs>
    <input type="file" ref="fileInput" accept="image/*" style="display: none" @change="handleFileChange" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import dayjs from "dayjs";
import { getRoleList, getRoleByUserId } from "@/views/system/authority/accountManage/index";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { getAllUserInfo } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { uploadImg } from "@/api/modules/upload";

// 获取用户信息类型
interface User {
  Log_Time: string;
  Log_IP: string;
  Log_Content: string;
  Log_ID: string;
  Log_IsHighRisk: boolean;
  Log_Type: string;
  Log_ChangMark: string;
}

const { proxy } = useCurrentInstance();
const userStore = useUserStore();
const router = useRouter();

const userInfo = JSON.parse(window.sessionStorage.getItem("user")).userInfo;
console.log(userInfo);

// 角色数组
const roleData = ref([]);

// 当前页
const currentPage = ref<number>(1);
// 当前的pagesize
const pageSize = ref<number>(30);
// 当前总条数
const total = ref<number>(0);
// 头像url
const avatorUrl = ref<string>("");

const tableRowClassName = ({ row, rowIndex }: { row: User; rowIndex: number }) => {
  if (rowIndex === 1) {
    return "warning-row";
  } else if (rowIndex === 3) {
    return "success-row";
  }
  return "";
};

const tableData = ref<User>();

// 定义引用
const fileInput = ref<HTMLInputElement | null>(null);

// 点击图片时触发文件选择框
const triggerFileSelect = () => {
  fileInput.value!.click();
};

// 文件选择后的处理
const handleFileChange = (event: Event) => {
  // 断言 target 为 HTMLInputElement 类型，并确保 files 存在
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];

  if (file) {
    if (file) {
      console.log("file------", file);
      let formData = new FormData();
      formData.append("file", file);
      formData.append("folderpath", "abc");
      uploadImg(formData).then(res => {
        console.log("上传成功", res);
        if (res.Mark && res.Model) {
          updateInfo(res.Model);
        }
      });
      // 清空文件输入框的值
      input.value = "";
    } else {
      console.warn("No file selected or file input is empty");
    }
    // 清空文件输入框的值
    input.value = "";
  } else {
    console.warn("No file selected or file input is empty");
  }
};

// 更新用户信息
const updateInfo = (picUrl: string) => {
  proxy.$vueAxios
    .post(
      "MasterBaseUsers/Update",
      {
        u_ID: userInfo.U_ID,
        u_Name: userInfo.U_Name,
        u_CName: userInfo.U_CName,
        u_Enable: userInfo.U_Enable,
        u_IsThird: userInfo.U_IsThird,
        u_Remark: userInfo.U_Remark,
        u_Order: userInfo.U_Order,
        u_IsAdministrator: userInfo.U_IsAdministrator,
        u_IsSuperAdministrator: userInfo.U_IsSuperAdministrator,
        u_Validity_Time: userInfo.U_Validity_Time ? dayjs(userInfo.U_Validity_Time).format("YYYY-MM-DD") : null,
        u_PasswordErrCount: userInfo.U_PasswordErrCount,
        u_ReadOnly: userInfo.U_ReadOnly,
        u_Picture: picUrl
      },
      { noLoading: true }
    )
    .then(async (res: any) => {
      console.log("-----成功替换", res);
      getCurUserInfo();
      // dialogSetting.visible = false;
      // await saveRole(relevanceData.value, clickObj.value.U_ID);
      // getTableData();
    });
};

// 获取用户信息
const getCurUserInfo = async () => {
  await getAllUserInfo(); // 获取所有用户数据
  const curInfo = userStore.getUserList.find((v: any) => v.U_ID === userInfo.U_ID);
  avatorUrl.value = import.meta.env.VITE_STATIC + curInfo.U_Picture || "";
};
getCurUserInfo(); // 调用一下获取

const getDateRange = (daysAgo: number = 10) => {
  const endTime = new Date(); // 当前日期
  const startTime = new Date();
  startTime.setDate(endTime.getDate() - daysAgo); // 往前推指定天数

  const formatDate = (date: any) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份补零
    const day = String(date.getDate()).padStart(2, "0"); // 日期补零
    return `${year}/${month}/${day}`;
  };

  return {
    startTime: formatDate(startTime),
    endTime: formatDate(endTime)
  };
};

// 当前每页多少条数据
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getLogData();
};
// 当前第几页
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getLogData();
};

// 获取登录信息
const { startTime, endTime } = getDateRange(1);
const getLogData = () => {
  proxy.$vueAxios
    .get("MasterBaseLog/getList", {
      startTime: startTime,
      endTime: endTime,
      keyword: "",
      isHighRisk: "",
      uId: userInfo.U_ID,
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    })
    .then((res: any) => {
      if (res) {
        console.log("res----", res);
        tableData.value = res.List;
        total.value = res.Count;
      }
    });
};
getLogData();

// 获取表格数据
const getRole = async () => {
  proxy.$showLoading();
  const res = await getRoleList(); // 获取角色选项数组list
  const ids = await getRoleByUserId(userInfo.U_ID);

  const role = res.filter(v => ids.includes(v.G_ID));
  roleData.value = role.map(j => j.G_Name);
  proxy.$hideLoading();
};

// 修改密码
const resetPassword = () => {
  router.push({ name: "resetPassword" });
};
onMounted(() => {
  getRole();
});
</script>

<style>
.tooltip-pop {
  max-width: 265px;
}
</style>

<style scoped lang="scss">
.userInfo {
  box-sizing: border-box;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  height: 100%;
  padding: 10px;
  overflow-y: scroll;
  background-color: var(--el-bg-color);
  .log-card {
    height: 99%;
    :deep(.el-tabs__content) {
      height: calc(100% - 70px);
    }
    .el-tab-pane {
      height: calc(100% - 32px);
    }
    .log-content {
      width: 265px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .userInfo_content {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 66%;
    height: 100%;
    margin: 0 auto;

    // justify-content: center;
    // padding-top: 30%;
    .content_title {
      padding: 64px 0 24px;
      font-size: 18px;
    }
    .content_avatar {
      width: 100px;
      height: 100px;
      margin: 10px 0 38px;
      cursor: pointer;
      border-radius: 50%;
    }
    .content_info {
      width: 100%;
      .info_item {
        display: flex;

        // justify-content: space-between;
        align-items: center;

        // padding: 12px 0;
        height: 60px;
        border-bottom: 1px solid #cccccc;
        .item_title {
          width: 90px;
          font-size: 16px;
          color: #a3a3a3;
          word-break: keep-all;
        }
        .chara {
          display: flex;
        }
      }
    }
  }
  :deep(.el-table__header) {
    tr {
      th {
        color: #000000;
      }
    }
  }
  .el-pagination {
    margin-top: 10px;
  }
  :deep(.el-input__wrapper) {
    color: #000000;
    background-color: #ffffff;
    box-shadow: none;
  }
  :deep(.el-tabs--border-card) {
    width: calc(100% - 440px);
  }
}
</style>
